package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@RequiredArgsConstructor
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    private final StringRedisTemplate redisTemplate;
    @Override
    public List<ShopType> queryList() {

        String key = "cache:shopType";
        String shopJson = redisTemplate.opsForValue().get(key);
        // 是否存在
        if(StrUtil.isNotBlank(shopJson)){
            // 存在返回
            JSONArray shopArray = JSONUtil.parseArray(shopJson);
            return JSONUtil.toList(shopArray,ShopType.class);
        }
        //不存在查数据库
        List<ShopType> shopTypeList = list();
        //不存在返回错误
        if(shopTypeList == null){
            return null;
        }
        //存在写入redis
        redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shopTypeList),30L, TimeUnit.MINUTES);
        //返回

        return shopTypeList;
    }
}
